#include "Initialize.h"
#include "simodo/lsp-server/ServerContext.h"

#include "simodo/variable/json/Rpc.h"
#include "simodo/variable/json/Serialization.h"

namespace simodo::lsp
{

void Initialize::work()
{
    if (_server.state() != ServerState::None
     || _jsonrpc.id() <= 0
     || _jsonrpc.params().type() != variable::ValueType::Object) {
        _server.log().critical("There are wrong parameter structure of 'initialize' command", variable::toJson(_jsonrpc.value()));
        /// @todo Скорректировать коды (и тексты) ошибок
        _server.sending().push(variable::JsonRpc(1, u"Invalid request", _jsonrpc.id()));
        return;
    }
    const std::shared_ptr<variable::Object> params_object = _jsonrpc.params().getObject();

    _params = lsp::parseClientParams(params_object);

    variable::JsonRpc server_response = _server.initialize(_params, _jsonrpc.id());

    if (!server_response.is_valid()) {
        _server.log().critical("Unable to create initialization structure", variable::toJson(_jsonrpc.value()));
        /// @todo Скорректировать коды (и тексты) ошибок
        _server.sending().push(variable::JsonRpc(3, u"Unable to create initialization structure", _jsonrpc.id()));
        return;
    }

    _server.sending().push(server_response);
}

}